<template>
  <div class="page-container">
    <div class="base-container left-box department-tree">
      <el-tree
        ref="companyTree"
        :data="companyList"
        :props="treeProps"
        :expand-on-click-node="false"
        node-key="id"
        highlight-current
        empty-text=""
        @node-click="handleCompanyChange"
      />
    </div>
    <div class="right-box">
      <el-form class="base-search-form" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入部门名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="所属公司" prop="companyId">
          <el-tree-select
            v-model="queryParams.companyId"
            :data="companyList"
            :render-after-expand="true"
            :props="treeProps"
            node-key="id"
            clearable check-strictly
          />
        </el-form-item> -->
        <el-form-item label="状态" prop="state">
          <el-select v-model="queryParams.state" placeholder="状态" clearable>
            <el-option
              v-for="dict in sys_company_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="base-container mb-50px">
        <el-row :gutter="10" class="mb-10px">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['company:department:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['company:department:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table border v-loading="loading" :data="departmentList">
          <el-table-column label="部门名称" align="center" prop="name" min-width="120" show-overflow-tooltip />
          <el-table-column label="部门负责人" align="center" prop="debtor" min-width="100" show-overflow-tooltip />
          <el-table-column label="所属公司" align="center" prop="companyId" min-width="150" show-overflow-tooltip />
          <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.state"
                active-value="1"
                inactive-value="2"
                inline-prompt
                active-text="启用"
                inactive-text="禁用"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updatedTime" width="160" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="100">
            <template #default="scope">
              <el-tooltip content="详情" placement="top">
                <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['company:department:query']"></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['company:department:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['company:department:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <Dialog v-model="showDialog" :title="dialogTitle">
      <edit-department 
        v-if="dialogType == 1"
        ref="editDepartment"
        :company-list="companyList"
        @cancel="cancel"
        @confirm="confirm"
      />
      <department-detail
        v-if="dialogType == 2"
        ref="departmentDetail"
        :company-list="companyList"
        @cancel="cancel"
      />
    </Dialog>
  </div>
</template>

<script setup name="Department">
import { listDepartment, delDepartment, updateDepartment } from "@/api/company/department"
import { getAllCompanies } from '@/api/company/company'
import EditDepartment from './edit.vue'
import DepartmentDetail from './detail.vue'
import { nextTick } from "vue"

const { proxy } = getCurrentInstance()
const { sys_company_status }  = proxy.useDict('sys_company_status')

const companyTree = ref()
const editDepartment = ref()
const departmentDetail = ref()
const departmentList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const showDialog = ref(false)
const dialogTitle = ref('')
const dialogType = ref(0)   // 1添加修改  2详情
const companyList = ref([])
const treeProps = {
  label: 'name',
  disabled: (data, node) => {
    return data.check == false
  },
  class: (data, node) => {
    return data.check == false ? 'disabled-label' : 'active-label'
  }
}

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    companyId: null,
    name: null,
    state: null
  }
})

const { queryParams } = toRefs(data)

const handleCompanyChange = (obj) => {
  if (obj.check == false) {
    companyTree.value.setCurrentKey(null)
  } else {
    queryParams.value.companyId = obj.id
    handleQuery()
  }
}

/** 公司列表 */
function getCompanyList() {
  getAllCompanies().then(res => {
    companyList.value = res.data || []
  })
}

/** 查询公司部门列表 */
function getList() {
  loading.value = true
  listDepartment(queryParams.value).then(response => {
    departmentList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  showDialog.value = false
  dialogTitle.value = ''
  dialogType.value = 0
}

function confirm() {
  cancel()
  getList()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.companyId = null
  companyTree.value.setCurrentKey(null)
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 部门详情 */
function handleDetail(row) {
  showDialog.value = true
  dialogTitle.value = '部门详情'
  dialogType.value = 2
  nextTick(() => {
    departmentDetail.value.pageInit(row.id)
  })
}

/** 新增按钮操作 */
function handleAdd() {
  showDialog.value = true
  dialogTitle.value = '添加部门'
  dialogType.value = 1
  nextTick(() => {
    editDepartment.value.pageInit(null, queryParams.value.companyId)
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _id = row.id || ids.value
  showDialog.value = true
  dialogTitle.value = '修改部门'
  dialogType.value = 1
  nextTick(() => {
    editDepartment.value.pageInit(_id)
  })
}

/** 状态修改 */
function handleStatusChange(row) {
  let text = row.state == 1 ? "启用" : "禁用"
  proxy.$modal.confirm('确认要"' + text + '""' + row.name + '"部门吗?').then(function () {
    const params = {
      id: row.id,
      state: row.state,
      companyId: 'state'
    }
    return updateDepartment(params)
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
  }).catch(function () {
    row.state = row.state == 1 ? 2 : 1
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除该部门？').then(function() {
    return delDepartment(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('company/department/export', {
    ...queryParams.value
  }, `部门列表_${proxy.getFileImportName()}.xlsx`)
}

getCompanyList()
getList()
</script>

<style lang="scss" scoped>
.page-container {
  position: absolute;
  width: 100%;
  height: 100%;
  margin-left: -10px;
  padding-left: 10px;
  margin-top: -10px;
  padding-top: 10px;
  overflow: hidden;
}

.left-box {
  position: absolute;
  width: 210px;
  height: 100%;
  z-index: 15;
  overflow-y: scroll;
}

.right-box {
  position: relative;
  margin-left: 210px;
  padding-left: 10px;
  // padding-top: 3px;
  padding-right: 10px;
  width: calc(100% - 210px);
  height: calc(100% - 10px);
  overflow-y: scroll;  
}

::-webkit-scrollbar {
  display: none;
}

.w-210px {
  width: 210px;
  flex-shrink: 0;
}

.table {
  transition: width 0.23s ease-in-out;
}

.openSidebar .page-container .pagination-container {
  left: 430px !important;
}

.hideSidebar .page-container .pagination-container {
  left: 286px !important;
}
</style>
